package com.finger.gulimall.ware.service.impl;

import com.finger.gulimall.ware.entity.WareSkuEntity;
import com.finger.gulimall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.common.utils.PageUtils;
import com.finger.common.utils.Query;

import com.finger.gulimall.ware.dao.WareInfoDao;
import com.finger.gulimall.ware.entity.WareInfoEntity;
import com.finger.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /*
            page: 1
            limit: 10
            key:
         */
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper
                    .eq("id", key)
                    .or().like("name", key)
                    .or().like("address", key)
                    .or().eq("areacode", key);
        }


        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据skuId查询出对应的商品是否有库存
     * @param ids
     * @return
     */
    @Override
    public Map<Long,Boolean> getStockForOrderConfirm(List<Long> ids) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("sku_id",ids).select("sku_id","stock");
        List<WareSkuEntity> wareSkuEntities = wareSkuService.list(queryWrapper);
        Map<Long, Boolean> collect = wareSkuEntities.stream().collect(Collectors.toMap(WareSkuEntity::getSkuId, item -> {
            return item.getStock() > 0;
        }));
        return collect;
    }
}